ReactJS Ultra For Beginners

🔄 The useReducer Hook


What is useReducer?

  • A React Hook for managing complex state logic
  • Alternative to useState when state logic is complex
  • Based on the reducer pattern (like Redux)
  • Takes a reducer function and initial state

📝 Basic Syntax

import { useReducer } from "react"; function reducer(state, action) { switch (action.type) { case "increment": return { count: state.count + 1 }; case "decrement": return { count: state.count - 1 }; case "reset": return { count: 0 }; default: throw new Error(); } } function Counter() { const [state, dispatch] = useReducer(reducer, { count: 0 }); return ( <div> Count: {state.count} <button onClick={() => dispatch({ type: "increment" })}>+</button> <button onClick={() => dispatch({ type: "decrement" })}>-</button> <button onClick={() => dispatch({ type: "reset" })}>Reset</button> </div> ); }

🔑 Core Concepts

1. Reducer Function:

function reducer(state, action) { switch (action.type) { case "ADD_TODO": return { ...state, todos: [...state.todos, action.payload], }; case "TOGGLE_TODO": return { ...state, todos: state.todos.map((todo) => todo.id === action.payload ? { ...todo, completed: !todo.completed } : todo ), }; case "DELETE_TODO": return { ...state, todos: state.todos.filter((todo) => todo.id !== action.payload), }; default: return state; } }

2. Initial State:

const initialState = { todos: [], filter: "all", }; const [state, dispatch] = useReducer(reducer, initialState);

3. Dispatch Actions:

// Simple action dispatch({ type: "ADD_TODO", payload: newTodo }); // Action with payload dispatch({ type: "UPDATE_USER", payload: { id: 1, name: "John" }, });

🎯 Common Patterns

Todo List Example:

const initialState = { todos: [], filter: "all", }; function todoReducer(state, action) { switch (action.type) { case "ADD_TODO": return { ...state, todos: [ ...state.todos, { id: Date.now(), text: action.payload, completed: false, }, ], }; case "TOGGLE_TODO": return { ...state, todos: state.todos.map((todo) => todo.id === action.payload ? { ...todo, completed: !todo.completed } : todo ), }; case "DELETE_TODO": return { ...state, todos: state.todos.filter((todo) => todo.id !== action.payload), }; case "SET_FILTER": return { ...state, filter: action.payload, }; default: return state; } } function TodoApp() { const [state, dispatch] = useReducer(todoReducer, initialState); const addTodo = (text) => { dispatch({ type: "ADD_TODO", payload: text }); }; const toggleTodo = (id) => { dispatch({ type: "TOGGLE_TODO", payload: id }); }; const deleteTodo = (id) => { dispatch({ type: "DELETE_TODO", payload: id }); }; const setFilter = (filter) => { dispatch({ type: "SET_FILTER", payload: filter }); }; return ( <div> <AddTodo onAdd={addTodo} /> <TodoList todos={state.todos} onToggle={toggleTodo} onDelete={deleteTodo} /> <FilterButtons filter={state.filter} onFilterChange={setFilter} /> </div> ); }

🔧 Advanced Patterns

Lazy Initialization:

function init(initialCount) { return { count: initialCount }; } function reducer(state, action) { switch (action.type) { case "increment": return { count: state.count + 1 }; case "decrement": return { count: state.count - 1 }; case "reset": return init(action.payload); default: throw new Error(); } } function Counter({ initialCount }) { const [state, dispatch] = useReducer(reducer, initialCount, init); return ( <> Count: {state.count} <button onClick={() => dispatch({ type: "reset", payload: initialCount })} > Reset </button> </> ); }

Async Actions:

function userReducer(state, action) { switch (action.type) { case "FETCH_USER_START": return { ...state, loading: true, error: null }; case "FETCH_USER_SUCCESS": return { ...state, user: action.payload, loading: false }; case "FETCH_USER_ERROR": return { ...state, error: action.payload, loading: false }; default: return state; } } function UserProfile({ userId }) { const [state, dispatch] = useReducer(userReducer, { user: null, loading: false, error: null, }); useEffect(() => { const fetchUser = async () => { dispatch({ type: "FETCH_USER_START" }); try { const user = await fetchUserAPI(userId); dispatch({ type: "FETCH_USER_SUCCESS", payload: user }); } catch (error) { dispatch({ type: "FETCH_USER_ERROR", payload: error.message }); } }; fetchUser(); }, [userId]); if (state.loading) return <div>Loading...</div>; if (state.error) return <div>Error: {state.error}</div>; if (!state.user) return <div>No user found</div>; return <div>Welcome, {state.user.name}!</div>; }

🎯 When to Use useReducer

Use useReducer when:

  • State logic is complex
  • State has multiple sub-values
  • State updates depend on previous state
  • You want to centralize state logic

Use useState when:

  • State is simple (boolean, string, number)
  • State updates are independent
  • State logic is straightforward

⚠️ Best Practices

  1. Keep reducers pure - no side effects
  2. Use descriptive action types
  3. Include payload in actions for data
  4. Handle all cases in switch statement
  5. Use TypeScript for better type safety
  6. Extract complex logic into separate functions

🔄 Comparison with useState

useState (Simple):

const [count, setCount] = useState(0); setCount(count + 1);

useReducer (Complex):

const [state, dispatch] = useReducer(reducer, { count: 0 }); dispatch({ type: "increment" });